<template>
  <div class="tp">
    <Header />

    <Content>
      <div class="cp">
        <div class="card">
          <div class="c-title"> 基本信息 </div>

          <div class="line"></div>

          <div class="c-body">
            <BasicForm @register="registerForm1" />
          </div>
        </div>

        <div class="card">
          <div class="c-body" style="padding-top: 0">
            <BasicTable
              @register="registerTable"
              :dataSource="state.dataSource"
              :scroll="{ y: 320 }"
              style="margin: 0 -2px"
            >
              <template #tableTitle>
                <div class="c-title"> 商品明细 </div>
              </template>
            </BasicTable>
          </div>
        </div>
      </div>
    </Content>

    <Footer>
      <a-flex align="center" justify="center" gap="middle" class="f-body">
        <a-button @click="router.back()"> 取消</a-button>

        <a-popconfirm title="您确定要出库吗" ok-text="确定" cancel-text="取消" @confirm="onSubmit">
          <a-button type="primary">确定出库 </a-button>
        </a-popconfirm>
      </a-flex>
    </Footer>
  </div>
</template>

<script setup>
  import { defineOptions, h, onMounted, reactive, ref } from 'vue';

  import { BasicTable, useTable } from '@/components/Table';

  import Header from '@/widget/header.vue';
  import Content from '@/widget/content.vue';
  import { POST } from '@/api/http';
  import { moveTypeCodeList } from '@/api/ds';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useRoute, useRouter } from 'vue-router';
  import { BasicForm, useForm } from '@/components/Form';
  import ProImgCell from '@/widget/pro-img-cell.vue';
  import { InputNumber } from 'ant-design-vue';
  import Footer from '@/widget/footer.vue';
  import { isNil } from '@/api/util.js';

  defineOptions({ name: 'StockOut2' });

  const route = useRoute(),
    router = useRouter();

  const { createMessage } = useMessage();

  const { goodsSn = null, stockType = null } = route.query;
  const detail = ref({});
  const state = reactive({ dataSource: [] });

  const [registerForm1, form1] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24, style: { paddingRight: '36px' } },

    schemas: [
      {
        label: '出库原因',
        field: 'moveTypeCode',
        required: true,
        component: 'Select',
        componentProps: {
          options: moveTypeCodeList.filter((o) => o.category === 'D'),
        },
        colProps: {
          span: 24,
        },
        itemProps: {
          wrapperCol: {
            span: 6,
          },
        },
      },

      {
        label: '备注',
        field: 'logNote',
        required: false,
        component: 'InputTextArea',
        componentProps: {
          maxlength: 100,
        },
        colProps: {
          span: 24,
        },
        itemProps: {
          wrapperCol: {
            span: 10,
          },
        },
      },
    ],
    showActionButtonGroup: false,
  });

  onMounted(() => {
    loadData();
  });

  async function loadData() {
    const result = (await POST('/product/getStockDetail', { goodsSn })) ?? {};

    // const { stockDetailBeanList } = result;
    // state.dataSource = stockDetailBeanList?.filter((o) => o.stockType === stockType) ?? [];
    state.dataSource = [result];
    detail.value = result;
  }

  const [registerTable] = useTable({
    pagination: false,
    columns: [
      {
        title: '商品名称',
        dataIndex: 'goodsName',
        ellipsis: false,
        width: 290,
        customRender: ({ value: title }) => h(ProImgCell, { src: detail.value.goodsImage, title }),
      },
      {
        title: '规格',
        dataIndex: 'specs',
        ellipsis: false,
        customRender: () => detail.value.specs,
      },

      {
        title: '库存数量',
        dataIndex: 'lastSyncStock',
        ellipsis: false,
        customRender: ({ value }) => `${value || '0'}${detail.value.saleUnit || ''}`,
      },

      {
        title: '出库数量',
        dataIndex: 'qty',
        ellipsis: false,
        customRender: ({ value, record }) => {
          return h('div', null, [
            h(InputNumber, {
              value,
              min: 0,
              style: { width: '160px !important' },
              addonAfter: detail.value.saleUnit || '',
              precision: 0,
              ['onUpdate:value']: (nVal) => {
                record.qty = nVal;
              },
            }),
          ]);
        },
      },
    ],
    useSearchForm: false,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: false,
    rowKey: 'goodsSn',
  });

  const formList = [form1];

  async function onSubmit() {
    await Promise.all(formList.map((f) => f.validate()));
    const formData = formList.reduce((prev, f) => Object.assign(prev, f.getFieldsValue()), {});

    //保存
    const { moveTypeCode } = formData;
    const data = { ...formData };
    data.moveType = moveTypeCodeList.find((o) => o.value === moveTypeCode)?.category;

    const { dataSource } = state;
    if (dataSource.length < 1) {
      createMessage.error(`商品明细不能为空`);
      return;
    }

    for (const { goodsName, qty } of dataSource) {
      if (isNil(qty) || qty < 1) {
        createMessage.error(`请输入“${goodsName}”出库数量`);
        return;
      }
    }

    data.detailList = dataSource.map(({ goodsSn, qty }) => ({
      goodsSn,
      qty,
    }));

    await POST('/product/productStoreOrDeliver', data);
    createMessage.success('已完成出库');
    await router.back();
  }
</script>
<style lang="less" scoped>
  .card {
    margin-bottom: 24px;
    padding: 12px;

    .c-title {
      color: #333;
      font-size: 14px;
      font-weight: 500;
    }

    .line {
      margin: 0 -12px;
      padding-bottom: 8px;
      border-bottom: 1px solid #f0f0f0;
    }

    .c-body {
      padding: 18px 12px;
    }
  }
</style>
